﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Abp.AspNetCore;
using Castle.Facilities.Logging;
using Abp.Castle.Logging.Log4Net;
using NRSoft.IdentityServer.SSOServer.TestData;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Http;
using Exceptionless;

namespace NRSoft.IdentityServer.SSOServer
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            // 添加IdentityServer4相关的配置
            services.AddIdentityServer(options =>
            {
                // 配置Cookie过期时间
                options.Authentication.CookieLifetime = new TimeSpan(0, 10, 0);
                options.Authentication.CookieSlidingExpiration = false;

                // IdentityServer4 配置负载均衡，确保发行者名称一致
                // 参考网址：http://www.cnblogs.com/xishuai/p/identityserver4-slb.html
                options.IssuerUri = "https://qasso.avischina.cn";

                // 此服务器实例的来源，例如https://myorigin.com。 如果未设置，则从请求推断出原始名称。
                // 解决发布的uri都是http，不是https 的问题
                // 参考网址：https://www.cnblogs.com/chenzhe/p/7844790.html
                options.PublicOrigin = "https://qasso.avischina.cn";
            })
            .AddDeveloperSigningCredential()
            .AddInMemoryClients(ConfigTestData.GetClients())
            .AddInMemoryApiResources(ConfigTestData.GetApiResources())
            .AddInMemoryIdentityResources(ConfigTestData.GetIdentityResources());

            // 配置认证Cookie信息
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(options =>
            {
                options.Cookie.Name = "nrsoft.auth";
                options.LoginPath = new PathString("/Account/Login");
            });

            // 配置强制跳Https
            //services.AddHttpsRedirection(options =>
            //{
            //    options.RedirectStatusCode = StatusCodes.Status301MovedPermanently;
            //    options.HttpsPort = 443;
            //});

            // 配置ABP和依赖注入。应该在最后执行。
            return services.AddAbp<SSOServerWebModule>(options =>
            {
                // 配置Log4net日志记录（可选）
                options.IocManager.IocContainer.AddFacility<LoggingFacility>(
                    f => f.UseAbpLog4Net().WithConfig("log4net.config")
                );
            });
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            // 初始化ABP框架和所有模块（module）。必须要先执行
            app.UseAbp(options =>
            {
                // 禁用安全Header，否则Client中放置iframe会被阻止。（x-frame-options: SAMEORIGIN）
                options.UseSecurityHeaders = false;
            });

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            // 启用IdentityServer4
            app.UseIdentityServer();

            //app.UseHttpsRedirection();
            app.UseStaticFiles();
            //app.UseCookiePolicy();

            // 启动Exceptionless 查看apiKey的位置：管理中心 -> 项目管理 -> 修改 -> API -> 密钥
            app.UseExceptionless("mxBh1SbK2SVKcEqFQKC6NurVb11l5KRLtqGkaGS7");

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}
